<?php

namespace app\common\service;

use app\common\model\SystemDictType;
use app\common\model\SystemDictData;
use support\Cache;

/**
 * 系统字典服务
 */
class SystemDictService
{
    /**
     * 获取字典数据
     * @param string $dictCode 字典标识
     * @return array
     */
    public static function getDictData(string $dictCode): array
    {
        $cacheKey = 'dict_data_' . $dictCode;
        
        // 尝试从缓存获取
        $data = Cache::get($cacheKey);
        if ($data !== null) {
            //return $data;
        }
        
        // 从数据库获取
        $dictType = SystemDictType::where('code', $dictCode)
            ->where('status', 1)
            ->find();
            
        if (!$dictType) {
            return [];
        }
        
        $data = SystemDictData::where('type_id', $dictType['id'])
            ->where('status', 1)
            ->order('sort', 'asc')
            ->select()
            ->toArray();
            
        // 格式化数据
        $result = [];
        foreach ($data as $item) {
            $result[] = [
                'value' => $item['value'],
                'label' => $item['label'],
                'remark' => $item['remark'],
            ];
        }
        
        // 缓存1小时
        Cache::set($cacheKey, $result, 3600);
        return $result;
    }
    
    /**
     * 清除字典缓存
     * @param string|null $dictCode 字典标识，null表示清除所有
     */
    public static function clearCache(?string $dictCode = null): void
    {
        if ($dictCode) {
            Cache::delete('dict_data_' . $dictCode);
        } else {
            // 清除所有字典缓存
            $keys = Cache::get('dict_keys') ?: [];
            foreach ($keys as $key) {
                if (strpos($key, 'dict_data_') === 0) {
                    Cache::delete($key);
                }
            }
            Cache::delete('dict_keys');
        }
    }
}